package byx.container.annotation.extension.impl;

import byx.container.annotation.annotation.Inject;
import byx.container.annotation.extension.core.ParameterHandler;
import byx.container.annotation.extension.core.ParameterInfo;
import byx.container.core.Container;
import byx.container.core.ObjectFactory;
import byx.container.core.utils.ReflectUtils;

import static byx.container.core.ObjectFactories.fromContainer;
import static byx.container.core.ObjectFactories.value;

/**
 * 自定义注入参数处理器
 */
public class CustomInjectParameterHandler implements ParameterHandler {
    @Override
    public boolean support(ParameterInfo param) {
        return param.getAnnotationMetadata().isAnnotationPresent(Inject.class);
    }

    @Override
    public ObjectFactory<?> handle(ParameterInfo param, Container container) {
        Inject inject = param.getAnnotationMetadata().getAnnotation(Inject.class);
        Class<? extends CustomInjector> injectorType = inject.value();
        boolean fromContainer = inject.fromContainer();

        if (fromContainer) {
            return fromContainer(container, injectorType)
                    .call(CustomInjector::getObjectFactory, value(container))
                    .call(ObjectFactory::create);
        } else {
            CustomInjector injector = ReflectUtils.createByDefaultConstructor(injectorType);
            return injector.getObjectFactory(container);
        }
    }
}
